﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WebLibraryMaker
{
    public static class Backup
    {
        public static void CheckBackup(Pathes pathes)
        {
            Stream hashFile = File.OpenRead(pathes.OutputDll);

            if (File.Exists(pathes.OutputDll + ".hash") && Convert.ToBase64String(MD5.Create().ComputeHash(hashFile)) == File.ReadAllText(pathes.OutputDll + ".hash"))
            {
                // the library was already processed
                hashFile.Close();
                Utils.TryCopy(pathes.OutputFileBillet + ".dll.bak", pathes.OutputFileBillet + ".dll");
                Utils.TryCopy(pathes.OutputFileBillet + ".pdb.bak", pathes.OutputFileBillet + ".pdb");
                Utils.TryCopy(pathes.OutputFileBillet + ".xml.bak", pathes.OutputFileBillet + ".xml");
            }
            else
            {
                //the library is new
                hashFile.Close();
                Utils.TryCopy(pathes.OutputFileBillet + ".dll", pathes.OutputFileBillet + ".dll.bak");
                Utils.TryCopy(pathes.OutputFileBillet + ".pdb", pathes.OutputFileBillet + ".pdb.bak");
                Utils.TryCopy(pathes.OutputFileBillet + ".xml", pathes.OutputFileBillet + ".xml.bak");
            }
        }

        public static void CreateBackup(Pathes pathes)
        {
            //copy result to intermediate directory
            Utils.TryCopy(pathes.OutputDll, pathes.IntermediateDll);            
            Utils.TryCopy(pathes.OutputFileBillet + ".pdb", pathes.IntermediateFileBillet + ".pdb");            

            //calculate the hash
            Stream hashFile = File.OpenRead(pathes.OutputDll);
            File.WriteAllText(pathes.OutputDll + ".hash", Convert.ToBase64String(MD5.Create().ComputeHash(hashFile)));
            hashFile.Close();
        }
    }
}
